package com.longjianghuasheng.logistics.business.order.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PathUtils
import com.longjianghuasheng.logistics.base.BaseMultiStateViewModel
import com.longjianghuasheng.logistics.data.model.bean.ApiResponseNoData
import com.longjianghuasheng.logistics.entity.SignInfo
import com.longjianghuasheng.logistics.ext.commit2
import com.longjianghuasheng.logistics.ext.toastNormal
import com.longjianghuasheng.logistics.network.apiService
import com.longjianghuasheng.logistics.repository.request.HttpRequestCoroutine
import com.longjianghuasheng.logistics.util.CacheUtil
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.FileCallBack
import okhttp3.Call
import okhttp3.Request
import java.io.File

class SignUpViewModel : BaseMultiStateViewModel() {

    var id = 0

    val list = mutableListOf<String>()

    val result by lazy {
        MutableLiveData<SignInfo>()
    }

    val notify by lazy {

        MutableLiveData<ApiResponseNoData>()
    }

    val fileSuccess by lazy {
        MutableLiveData<String>()
    }

    fun sign_info() {
        getData({ apiService.sign_info(id) }, result)

    }

    fun sign_files() {
        if (list.isEmpty()) {
            toastNormal("请选择文件")
            return
        }

        commit2({ HttpRequestCoroutine.sign_files(list.toTypedArray(), id) }, notify)
    }


    fun startDownload(fileUri: String) {
        OkHttpUtils.get()
            .url(fileUri)
            .build()
            .execute(object : FileCallBack(
                getCacheFileDir(),
                getFileNameByUrl(fileUri)
            ) {
                override fun onBefore(request: Request, id: Int) {
                    loadingChange.showDialog.postValue("")
//                    getMessageLoader("文件下载中...").show()
                    LogUtils.d(TAG, "文件下载中...")
                }

                override fun inProgress(progress: Float, total: Long, id: Int) {
//                    getMessageLoader().updateMessage("文件下载中(" + (progress * 100).toInt() + "%)")
                    val toInt = (progress * 100).toInt()
                    LogUtils.d(TAG, "文件下载中($toInt%)")


                }

                override fun onError(call: Call, e: Exception, id: Int) {
                    loadingChange.dismissDialog.postValue(false)
                    LogUtils.d(TAG, "error=$e------call=$call")

                }

                override fun onResponse(response: File, id: Int) {
                    loadingChange.dismissDialog.postValue(false)

//                    getMessageLoader().dismiss()
                    LogUtils.d(TAG, "onResponse")

                    //保存缓存文件的路径
                    val filePath = response.path
                    CacheUtil.setFilePath(fileUri, filePath)
                    fileSuccess.postValue(filePath)
                }
            })

    }

    fun getCacheFileDir(): String = PathUtils.getExternalDocumentsPath() + File.separator + "x5"

    /**
     * 根据下载地址获取文件名
     *
     * @param url
     * @return
     */
    fun getFileNameByUrl(url: String): String {
        return EncryptUtils.encryptMD5ToString(url) + "." + getFileType(url)
    }

    /***
     * 获取文件类型
     */
    private fun getFileType(paramString: String): String? {
        var str: String? = ""
        if (TextUtils.isEmpty(paramString)) {
            return str
        }
        val i = paramString.lastIndexOf('.')
        if (i <= -1) {
            return str
        }
        str = paramString.substring(i + 1)
        return str
    }

    companion object {

        const val TAG = "SignUpViewModel"
    }

}